<template>
	<view class="page">
		<view class="page-tips">
			群发消息需选注册名片，方便用户联系你
		</view>
		<view class="main">
			<view class="form-wrap">
				<u-form labelWidth="220rpx">
					<u-form-item label="企业名称：" prop="name" required borderBottom>
						<u-input v-model="company.name" border="none" inputAlign="right" disabled disabledColor="#fff"
							placeholder="请输入企业名称" />
					</u-form-item>
					<u-form-item label="产品名称：" prop="productName" required>
						<u-input v-model="form.productName" border="none" inputAlign="right" placeholder="请输入产品名称" />
					</u-form-item>
				</u-form>
			</view>
			<view class="page-title">
				产品图片、视频上传（视频可不添加）
			</view>
			<view style="display: flex;flex-wrap: wrap;">
				<view class="" :style="{width: 160*(fileList1.length+1)+'rpx'}">
					<u-upload style="flex: auto;" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" multiple width="144rpx" name="1"
						height="144rpx">
						<view class="add-img">
							<view class="icon">
								<u-icon name="camera-fill" color="#aaaaaa" size="28"></u-icon>
							</view>
							<text>1张即可</text>
						</view>
					</u-upload>
				</view>
				<u-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" width="144rpx" name="2"
					accept="video" :max-count="1" height="144rpx">
					<view class="add-img">
						<view class="icon">
							<u-icon name="play-right-fill" color="#aaaaaa" size="28"></u-icon>
						</view>
						<text>添加视频</text>
					</view>
				</u-upload>
			</view>
			<view class="form-wrap" style="padding-bottom: 24rpx;">
				<view class="page-title">
					产品卖点
				</view>
				<piaoyiEditor :values="values" :maxlength="3000" @changes="saveContens" :readOnly="readOnly"
					:photoUrl="photoUrl" :api="api" :name="name" />
			</view>
			<view class="form-wrap">
				<u-form labelWidth="220rpx">
					<u-form-item label="产品分类：" prop="typeName" required borderBottom @click="typeShow = true">
						<u-input v-model="form.typeName" border="none" inputAlign="right" placeholder="请选择产品分类"
							disabled disabledColor="#fff" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="毛利率：" prop="mll" borderBottom>
						<u-input v-model="form.mll" border="none" inputAlign="right"
							placeholder="请输入毛利率" />
					</u-form-item>
					<u-form-item label="建议售价：" prop="price" borderBottom>
						<u-input v-model="form.price" border="none" type="digit" inputAlign="right"
							placeholder="请输入建议售价" />
					</u-form-item>
					<u-form-item label="产地：" prop="chandi" @click="provincesShow = true">
						<u-input v-model="form.chandi" border="none" inputAlign="right" placeholder="请选择产地" disabled disabledColor="#fff" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
				</u-form>
			</view>
			<view class="form-wrap">
				<u-form labelWidth="220rpx">
					<u-form-item label="联系人：" prop="memberName" required borderBottom>
						<u-input v-model="form.memberName" border="none" inputAlign="right" placeholder="请输入联系人" />
					</u-form-item>
					<u-form-item label="职务：" prop="position" borderBottom>
						<u-input v-model="form.position" border="none" inputAlign="right" placeholder="请输入职务" />
					</u-form-item>
					<u-form-item label="负责区域：" prop="fzqy" borderBottom @click="fzqyShow = true">
						<u-input v-model="form.fzqy" placeholder="点击选择" border="none" inputAlign="right" disabled
							disabledColor="#ffffff" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="电话：" prop="mobile" required>
						<u-input v-model="form.mobile" border="none" inputAlign="right" placeholder="请输入电话" />
					</u-form-item>
				</u-form>
			</view>
		</view>
		<view class="btm-wrap-tc">

		</view>
		<view class="btm-wrap">
			<view class="btn return-btn" @click="toLook">
				预览产品
			</view>
			<view class="btn confim-btn" @click="submit">
				立即发布
			</view>
		</view>
		<u-picker :show="typeShow" ref="uPicker" :columns="columns" @confirm="confirm" @change="changeHandler"
			:loading="loading" keyName="typeName"></u-picker>
		<u-popup :show="fzqyShow" @close="fzqyShow = false">
			<view style="padding: 32rpx;">
				<u-checkbox-group v-model="form.fzqy" placement="column">
					<u-checkbox :customStyle="{marginBottom: '8px'}" v-for="(item, index) in fuzeArea" :key="index"
						:label="item.dictLabel" :name="item.dictLabel">
					</u-checkbox>
				</u-checkbox-group>
				<u-button type="primary" shape="circle" text="确定" @click="fzqyShow = false"></u-button>
			</view>
		</u-popup>
		<u-picker :show="provincesShow" :columns="provinces" @cancel="provincesShow = false"
			@confirm="chooseProvinces"></u-picker>
	</view>
</template>

<script>
	import piaoyiEditor from '@/uni_modules/piaoyi-editor/components/piaoyi-editor/piaoyi-editor.vue';

	export default {
		data() {
			return {
				form: {
					companyId: null,
					productName: '',
					productImg: '',
					productVedio: '',
					content: '',
					mll: '',
					price: '',
					chandi: '',
					memberName: '',
					position: '',
					fzqy: '',
					mobile: '',
					typeName: '',
					typeId: '',
					id: null
				},
				fileList1: [],
				fileList2: [],
				readOnly: false, //是否只读
				photoUrl: this.$fileServer, //服务器图片域名或者ip
				api: '/dev-api/api/member/uploadFile.client', //上传图片接口地址
				txt: '',
				name: 'upload',
				values: '',
				company: {},
				columns: [
					[],
					[]
				],
				typeShow: false,
				loading: false,
				fzqyShow: false,
				fuzeArea: [],
				provinces: [
					[
						'北京', '天津', '河北', '山西', '内蒙古',
						'辽宁', '吉林', '黑龙江', '上海', '江苏',
						'浙江', '安徽', '福建', '江西', '山东',
						'河南', '湖北', '湖南', '广东', '广西',
						'海南', '重庆', '四川', '贵州', '云南',
						'西藏', '陕西', '甘肃', '青海', '宁夏',
						'新疆', '台湾', '香港', '澳门'
					]
				],
				provincesShow: false,
			};
		},
		components: {
			piaoyiEditor
		},
		onLoad(o) {
			if (o.pid) {
				this.form.id = o.pid
				this.getProduct()
			} else {
				this.form.companyId = o.id
				this.getCompany()
			}
			this.$api.member.getDictList('fuzeAreaCode').then(res => {
				this.fuzeArea = res.data
			})
		},
		methods: {
			getProduct() {
				this.$api.company.getProductDetailById({
					productId: this.form.id
				}).then(res => {
					this.company = res.data.company
					let productImg = ''
					if (res.data.product.productImg.length > 0) {
						productImg = res.data.product.productImg.split(',').map(i => {
							return {
								url: this.$fileServer + i,
								path: i
							}
						})
						this.fileList1 = productImg
					}
					let productVedio = ''
					if (res.data.product.productVedio.length > 0) {
						productVedio = res.data.product.productVedio.split(',').map(i => {
							return {
								url: this.$fileServer + i,
								path: i
							}
						})
						this.fileList2 = productVedio
					}
					let productObj = {...res.data.product};
					productObj.fzqy = productObj.fzqy.split(',');
					this.form = {
						...productObj,
						productImg: productImg,
						productVedio: productVedio
					}
					this.values = res.data.product.content
				})
			},
			chooseProvinces(e) {
				this.form.chandi = e.value[0]
				this.provincesShow = false
			},
			toLook() {
				uni.navigateTo({
					url: "/pages/shop/detail/detail?type=look",
					success: (res) => {
						// 通过eventChannel向被打开页面传送数据
						let productImg = ''
						if (this.fileList1.length > 0) {
							productImg = this.fileList1.map(i => {
								return i.path
							})
						}
						let productVedio = ''
						if (this.fileList2.length > 0) {
							productVedio = this.fileList2.map(i => {
								return i.path
							})
						}
						res.eventChannel.emit('acceptDataFromOpenerPage', {
							detail: {
								...this.form,
								productImg: productImg,
								productVedio: productVedio,
							},
						})
					}

				})
			},
			submit() {

				if (uni.$u.test.isEmpty(this.form.typeId)) {
					uni.showToast({
						title: "请选择产品分类",
						icon: "none"
					})
					return false
				}
				if (uni.$u.test.isEmpty(this.form.memberName)) {
					uni.showToast({
						title: "请输入联系人",
						icon: "none"
					})
					return false
				}
				if (uni.$u.test.isEmpty(this.form.mobile)) {
					uni.showToast({
						title: "请输入电话",
						icon: "none"
					})
					return false
				}

				let productImg = ''
				if (this.fileList1.length > 0) {
					productImg = this.fileList1.map(i => {
						return i.path
					}).join(',')
				}
				let productVedio = ''
				if (this.fileList2.length > 0) {
					productVedio = this.fileList2.map(i => {
						return i.path
					}).join(',')
				}
				let form = {...this.form};
				form.fzqy = form.fzqy.join(',');
				// console.log(form)
				this.$api.company.saveProduct({
					...form,
					productImg: productImg,
					productVedio: productVedio,
				}).then(res => {
					uni.showToast({
						title: "保存成功",
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				})
			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					// this.loading = true
					this.getProductTypeList1(values[0][index].id)
					// picker.setColumnValues(1, this.columnData[index])
				}
			},
			// 回调参数为包含columnIndex、value、values
			confirm(e) {
				console.log('confirm', e)
				this.form.typeId = e.value[1].id
				this.form.typeName = e.value[1].typeName
				this.typeShow = false
			},
			getCompany() {
				this.$api.company.getCompanyDetailById({
					companyId: this.form.companyId
				}).then(res => {
					this.company = res.data.company
				})
				this.$api.company.getProductTypeList({
					productTypeId: 0
				}).then(res => {
					this.$refs.uPicker.setColumnValues(0, res.data)
					if (res.data.length > 0) {
						this.getProductTypeList1(res.data[0].id)
					}
				})
				
			},
			getProductTypeList1(id) {
				this.$api.company.getProductTypeList({
					productTypeId: id
				}).then(res => {
					this.$refs.uPicker.setColumnValues(1, res.data)
					this.loading = false
				})
			},
			saveContens(e) {
				this.form.content = e.html
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: this.$fileServer + result,
						path: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$serverUrl + '/api/member/uploadFile.client', //仅为示例，非真实的接口地址
						filePath: url,
						name: 'upload',
						success: (uploadFileRes) => {
							resolve(JSON.parse(uploadFileRes.data).data)
						}
					});
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: #F5F5F5;
		.add-img{width: 144rpx;height: 144rpx;background-color: #ededed;border-radius: 15rpx;
			text-align: center;color: #AAAAAA;font-size: 28rpx;
			.icon{display: flex;justify-content: space-around;margin-top: 30rpx;margin-bottom: 5rpx;}
		}
		.page-tips {
			width: 100%;
			background: #FCF5EF;
			color: #CC6C6C;
			height: 72rpx;
			line-height: 72rpx;
			text-align: center;
			font-weight: bold;
		}

		.main {
			position: relative;
			padding: 24rpx 30rpx;

			.page-title {
				height: 80rpx;
				line-height: 80rpx;
				font-size: 28rpx;
			}

			.form-wrap {

				background: #FFFFFF;
				border-radius: 20rpx;
				padding: 0 30rpx;
				margin-top: 24rpx;

				.tx-wrap {
					display: flex;
					width: 100%;
					justify-content: flex-end;
				}

				.tx {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;

				}
			}
		}
	}

	.btm-wrap-tc {
		width: 100%;
		height: 170rpx;

	}

	.btm-wrap {
		width: 100%;
		position: fixed;
		bottom: 50rpx;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: space-around;
		z-index: 99;

		.btn {
			width: 244rpx;
			height: 70rpx;
			border-radius: 42rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 26rpx;

			&.return-btn {
				border: 1px solid #EC2424;
				color: #EC2424;
				background-color: #FFFFFF;
			}

			&.confim-btn {
				color: #FFFFFF;
				background: #EC2424;
			}
		}
	}
</style>